package com.situ.stmall.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.situ.stmall.entity.Address;
import com.situ.stmall.entity.Order;
import com.situ.stmall.entity.User;
import com.situ.stmall.service.AddressService;
import com.situ.stmall.service.OrderService;

@Controller
@RequestMapping("/user/order")
public class OrderController {

	
	@Autowired
	private OrderService orderService;
	@Autowired
	private AddressService addressService;
	
	/**
	 * 添加订单
	 */
	@PostMapping("/add")
	public String add(@RequestParam("cartId")Integer[] cartIds, HttpSession session,Model model) {
		//去除用户Id
		User user =(User) session.getAttribute("user");
		//调用service层
		try {
			Order order = orderService.add(user.getId(), cartIds);
			model.addAttribute("order", order);
			
			//查询当前用户的地址信息
			List addresser = addressService.getByUserId(user.getId());
			model.addAttribute("addresses", addresser);
			
			return "/user/order";
		} catch (Exception e) {
			
			e.printStackTrace();
			
			model.addAttribute("error", e.getMessage());
			
			return "/user/error";
		}
		
	}
	
	
	/**
	 * 支付路径
	 */
	@GetMapping("/pay")
	public String pay(String orderId, Integer addressId,Model model) {
		
		//根据订单id，查询订单信息
		Order order = orderService.getById(orderId);
		
		//在利用model传递到pay页面中
		model.addAttribute("order", order);
		//在根据addressId查询地址信息
		
		Address address = addressService.getById(addressId);
		//再利用model传递到pay页面中
		model.addAttribute("address", address);
		//将收货地址写入数据库中
		order.setAddressId(addressId);
		orderService.update(order);
		
		return "user/pay";
	}
	
	@PostMapping("/pay")
	public String pay(String id,String paypwd,HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		
		try {
			int result = orderService.pay(id,paypwd,user.getId());
			//支付成功
			
			return "redirect:/user/order/list";
		} catch (Exception e) {
			// 支付失败
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "user/error";
		}
		
		
	}
	
	@GetMapping("/list")
	public String list() {
		return "user/orderList";
	}
}
